import Router from '@koa/router'

const codeMessage = {
    200: '请求成功',
    400: '参数错误',
    401: '未登录',
    403: '无权限',
    404: '资源不存在',
    500: '服务器错误',
} as const

// 格式化返回数据
export const resFormatter: Router.Middleware = async (ctx, next) => {
    try {
        await next()
        const body: any = ctx.body
        const code =
            ((body.code || ctx.status) as keyof typeof codeMessage) || 200
        const msg = body.msg || codeMessage[code]
        const data = code === 200 ? body.data || body : null

        ctx.status = 200
        ctx.body = {
            code,
            data,
            msg,
        }
    } catch (err: any) {
        ctx.status = 200
        ctx.body = {
            code: 500,
            msg: `${err.message}`,
            data: null,
        }
        return
    }
}
